<template>
  <div class="app-contanier">
    <!-- 新建固化配置 -->
    <div class="solidify-contanier">
      <el-button class="solidify-bt" size="large" type="primary" @click="handleOpenDialog()">
        新建固化配置
      </el-button>
    </div>
    <div class="table-container">
      <el-table v-loading="loading" :data="pageData" border style="width: 100%; margin-top: 10px">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column type="index" label="序号" align="center" />
        <el-table-column prop="tableName" label="主题表名称" align="center" />
        <el-table-column prop="dataPeriod" label="增量固化信息" align="center" />
        <el-table-column prop="executionCycle" label="执行周期" align="center" />
        <el-table-column prop="createUser" label="创建人" align="center" />
        <el-table-column prop="createTime" label="创建时间" align="center" />
        <el-table-column label="操作" width="180" align="center">
          <template #default="{ row }">
            <el-button link type="info" @click="testRun(row)">试运行</el-button>
            <el-button link type="success" @click="executeRun(row)">运行</el-button>
            <!-- 测试按钮 -->
            <el-button link type="primary" @click="handleOpenDialog(row.id)">编辑</el-button>
            <el-button link type="danger" @click="deleteRow(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="pageQuery.pageIndex"
        v-model:limit="pageQuery.pageSize"
        @pagination="handleQuery"
      />
    </div>
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="70%" destroy-on-close>
      <cured-configuration :id="solidifyId" @save="handleSave" @reset="handleReset" />
    </el-dialog>
    <!-- 运行结果对话框 -->
    <el-dialog v-model="resultDialogVisible" title="运行结果" width="800px" destroy-on-close>
      <el-table
        v-if="indicatorOperationalResponse && indicatorOperationalResponse.fileNames"
        :data="indicatorOperationalResponse.entityList || []"
        style="width: 100%"
      >
        <el-table-column
          v-for="fileName in indicatorOperationalResponse.fileNames"
          :key="fileName"
          :prop="fileName"
          :label="fileName"
        />
      </el-table>
      <div v-else-if="indicatorOperationalResponse" class="no-data">暂无数据</div>
      <div v-else class="loading">加载中...</div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
export default { name: "IndicatorSolidification" };
</script>
<script setup lang="ts">
import CuredConfiguration from "@/views/indicatorSolidification/component/curedConfiguration.vue";
import IndicatorSolidifyAPI, {
  SolidifyQuery,
  SolidifyPageResponse,
  IdParameter,
  IndicatorOperationalResponse,
} from "@/api/indicatorSolidification/index";

defineOptions({
  name: "IndicatorSolidification",
  inheritAttrs: false,
});

const dialog = reactive({
  visible: false,
  title: "新增",
});

const idParameter = reactive<IdParameter>({});

const pageData = ref<SolidifyPageResponse[]>();
const loading = ref(false);

const solidifyId = ref();

const OpenCuredConfig = ref(false);
const total = ref(20);

// 结果对话框可见性
const resultDialogVisible = ref(false);

const indicatorOperationalResponse = ref<IndicatorOperationalResponse>({});

// 错误处理
const handleError = (err: any) => {
  if (err.response) {
    ElMessage.error(`数据加载失败: ${err.response.data.message}`);
  } else if (err.request) {
    ElMessage.error("请求未收到响应，请检查网络连接");
  } else {
    ElMessage.error("请求失败，请稍后重试");
  }
};

const testRun = async (row: MetricItem) => {
  idParameter.id = row.id;
  try {
    const data = await IndicatorSolidifyAPI.TestRun(idParameter);
    // 确保数据结构正确
    if (data) {
      indicatorOperationalResponse.value = data;
      // 强制更新响应式数据
      indicatorOperationalResponse.value = { ...data };
      // 显示结果对话框
      resultDialogVisible.value = true;
    } else {
      // 处理数据为空的情况
      indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
      resultDialogVisible.value = true;
      ElMessage.warning("未获取到运行结果数据");
    }
  } catch (error) {
    console.log(error);
    handleError(error);
    // 确保对话框可以关闭
    indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
    resultDialogVisible.value = true;
  }
  console.log("运行结果:", indicatorOperationalResponse.value);
  console.log("运行:", row);
};

const executeRun = async (row: MetricItem) => {
  idParameter.id = row.id;
  try {
    const data = await IndicatorSolidifyAPI.Operational(idParameter);
    // 确保数据结构正确
    if (data) {
      indicatorOperationalResponse.value = data;
      // 强制更新响应式数据
      indicatorOperationalResponse.value = { ...data };
      // 显示结果对话框
      resultDialogVisible.value = true;
    } else {
      // 处理数据为空的情况
      indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
      resultDialogVisible.value = true;
      ElMessage.warning("未获取到运行结果数据");
    }
  } catch (error) {
    handleError(error);
    // 确保对话框可以关闭
    indicatorOperationalResponse.value = { fileNames: [], entityList: [] };
    resultDialogVisible.value = true;
  }
  console.log("运行结果:", indicatorOperationalResponse.value);
  console.log("运行:", row);
};

const pageQuery = reactive<SolidifyQuery>({ pageIndex: 1, pageSize: 10 });

// 查询
const handleQuery = async () => {
  loading.value = true;
  IndicatorSolidifyAPI.Page(pageQuery)
    .then((data) => {
      pageData.value = data.data;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};

async function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改";
    solidifyId.value = id;
  } else {
    dialog.title = "新增";
  }
}

async function deleteRow(row: any) {
  console.log(row.id);
}

// 处理保存和重置事件
const handleSave = () => {
  OpenCuredConfig.value = false;
  dialog.visible = false;
  // 刷新表格数据
  handleQuery();
  console.log("配置已保存，刷新表格数据");
};

const handleReset = () => {
  console.log("配置已重置");
};

const handleSizeChange = (val: number) => {
  pageQuery.pageSize = val;
  console.log(`每页条数：${pageQuery.pageSize}`);
};
const handleCurrentChange = (val: number) => {
  pageQuery.pageIndex = val;
  console.log(`当前页面: ${pageQuery.pageIndex}`);
};

onMounted(() => {
  handleQuery();
});
</script>
<style lang="scss">
.app-contanier {
  padding: 15px;
}

.solidify-contanier {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18px 10px;
  margin-bottom: 10px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}

.solidify-bt {
  width: 120px;
}

.table-container {
  padding: 18px 10px;
  margin-bottom: 10px;
  background-color: var(--el-bg-color-overlay);
  border: 1px solid var(--el-border-color-light);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-light);
}
</style>
